const cloud = require('wx-server-sdk')
const xlsx = require('node-xlsx')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const groupsCollection = db.collection('groups')

exports.main = async (event, context) => {
  const { planId } = event
  const wxContext = cloud.getWXContext()
  
  try {
    // 获取分组数据
    const plan = await groupsCollection.doc(planId).get()
    if (!plan.data) {
      throw new Error('分组计划不存在')
    }

    // 生成Excel数据
    const data = [
      ['分组结果'], // 标题
      ['创建时间', plan.data.createTime],
      ['总人数', plan.data.totalMembers],
      ['分组数', plan.data.groupCount],
      [], // 空行
      ['组名', '成员'] // 表头
    ]

    // 添加分组数据
    plan.data.groupNames.forEach((name, index) => {
      const members = plan.data.members
        .filter(m => m.groupIndex === index)
        .map(m => m.nickName)
        .join('、')
      data.push([name, members])
    })

    // 生成Excel文件
    const buffer = xlsx.build([{
      name: '分组结果',
      data
    }])

    // 上传到云存储
    const upload = await cloud.uploadFile({
      cloudPath: `exports/${planId}_${Date.now()}.xlsx`,
      fileContent: buffer
    })

    return {
      success: true,
      fileID: upload.fileID
    }
  } catch (err) {
    console.error(err)
    return {
      success: false,
      error: err.message
    }
  }
} 